package com.zf.bm.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 校验枚举类型的值
 * 判断值是否在枚举的值的范围内
 * @author zjy
 * @Date 2021/8/31 17:01
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;
    private String splitStr;
    private boolean allowMulti;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        splitStr = constraintAnnotation.splitStr();
        allowMulti = constraintAnnotation.allowMulti();
        strValues = constraintAnnotation.values().split(splitStr);
    }

    //校验数据是否合法
    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        if (o instanceof String) {
            if (allowMulti) {
                String[] array = ((String) o).split(splitStr);
                for (String s : array
                ) {
                    if (!isValid(s)) {
                        return false;
                    }
                }
                return true;

            } else {
                return isValid((String) o);
            }
        }else if(o instanceof Integer){
                return isValid(String.valueOf(o));
        }


        return false;
    }

    private boolean isValid(String value){
        for (String s : strValues) {
            if (s.equals(value)) {
                return true;
            }
        }
        return false;
    }


}